<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      custom-class="edit-base-station__dialog"
      width="400px"
      @close="onCancel"
    >
      <el-form
        :model="baseStationForm"
        :rules="baseStationFormRules"
        ref="baseStationForm"
        label-width="100px"
      >
        <el-form-item prop="name" label="基站名称">
          <el-input
            v-model.trim="baseStationForm.name"
            placeholder="请输入基站名称"
            minlength="2"
            maxlength="20"
            show-word-limit
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="sn" label="SN码">
          <el-input
            v-model.trim="baseStationForm.sn"
            placeholder="请输入SN码"
            minlength="6"
            maxlength="20"
            show-word-limit
            clearable
            @input="onInput"
          ></el-input>
        </el-form-item>
        <el-form-item prop="desc" label="简介">
          <el-input
            v-model.trim="baseStationForm.desc"
            placeholder="请输入简介"
            minlength="2"
            maxlength="50"
            show-word-limit
            type="textarea"
            :rows="3"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onCancel" size="small">取消</el-button>
        <el-button
          type="primary"
          @click="onSubmit"
          size="small"
          v-preventReClick
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { addBaseStation, editBaseStation } from '@/api/baseStation.js';
import { ERROR_CODE } from '@/api/api.js';

export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: function() {
        return false;
      },
    },
    mode: {
      type: String,
      default: function() {
        return 'add';
      },
    },
    schoolId: {
      type: String,
      default: function() {
        return '';
      },
    },
    info: {
      type: Object,
      default: function() {
        return {
          class: '',
          name: '',
        };
      },
    },
  },
  data() {
    let validatePass = (rule, value, callback) => {
      let reg = /^[\u4e00-\u9fa5a-zA-Z0-9（）_-]*$/;
      if (!reg.test(value)) {
        callback(new Error('只支持输入汉字、数字、字母、（）、-、_'));
      } else {
        callback();
      }
    };
    return {
      visible: this.dialogVisible,
      baseStationForm: {
        name: '',
        sn: '',
        desc: '',
      },
      baseStationFormRules: {
        name: [
          {
            required: true,
            message: '请输入2-20字符！',
            trigger: 'blur',
          },
          {
            min: 2,
            max: 20,
            message: '请输入2-20字符！',
            trigger: 'blur',
          },
          {
            validator: validatePass,
            trigger: 'blur'
          }
        ],
        sn: [
          {
            required: true,
            message: '请输入6-20字符！',
            trigger: 'blur',
          },
          {
            min: 6,
            max: 20,
            message: '请输入6-20字符！',
            trigger: 'blur',
          },
        ],
        desc: [
          {
            required: true,
            message: '请输入2-50字符！',
            trigger: 'blur',
          },
          {
            min: 2,
            max: 50,
            message: '请输入2-50字符！',
            trigger: 'blur',
          },
        ],
      },
    };
  },
  computed: {
    title() {
      return `${this.mode === 'add' ? '添加' : '编辑'}基站`;
    },
  },
  mounted() {
    if (this.mode === 'add') {
      this.baseStationForm = this.$options.data().baseStationForm;
    } else {
      this.baseStationForm = this.info;
    }
  },
  methods: {
    onInput(val) {
      val = val.replace(/[^a-zA-Z0-9]/g, '');
      this.baseStationForm.sn = val;
    },
    onSubmit() {
      this.$refs['baseStationForm'].validate((valid) => {
        if (valid) {
          this.submit(this.baseStationForm);
        }
      });
    },
    onCancel() {
      this.$emit('cancel');
    },
    async submit(e) {
      const params = {
        ...this.baseStationForm,
        schoolId: this.schoolId,
      };
      let res =
        this.mode === 'add'
          ? await addBaseStation(params)
          : await editBaseStation(params);
      let data = res[1];
      if (res[0]) {
        if (data.code === ERROR_CODE.REFRESH_LIST) {
          this.$emit('refresh');
        }
        return;
      }

      if (data && data.code === 0) {
        const isAdd = this.mode === 'add';
        this.$emit('refresh', !isAdd);
        this.$message({
          message: isAdd ? '新增基站成功！' : '编辑基站成功！',
          type: 'success',
          duration: 1500,
        });
        this.baseStationForm = this.$options.data().baseStationForm;
      }
    },
  },
};
</script>
<style>
.edit-base-station__dialog {
  .el-input--suffix .el-input__inner {
    padding-right: 65px;
  }
}
</style>
